package com.zg.nacos.web;

import cn.hutool.core.util.StrUtil;
import com.zg.common.core.R;
import com.zg.common.core.exception.E;
import com.zg.nacos.domain.req.*;
import com.zg.nacos.util.NacosUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;

import javax.validation.Valid;
import javax.websocket.server.PathParam;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>Description: </p>
 *
 * @author zhanfeng.liang
 * @since 2025/6/20 16:11
 */

@RestController
@RequestMapping("/nacos")
@Api(tags = "nacos服务")
@Slf4j
public class NacosNamespaceController {

    @Value("${spring.cloud.nacos.username}")
    private  String userName;
    @Value("${spring.cloud.nacos.password}")
    private  String password;

    @Autowired
    private WebClient webClient;

    @ApiOperation(value = "命名空间新增")
    @PostMapping("/namespace/add")
    public R addNamespaces(@Valid @RequestBody NamespaceAddReq addReq) {

        Map map = namespace(addReq.getNacosToken());

        List<Map<String,String>> data=(List<Map<String,String>>)map.get("data");
        List list =data.stream().filter(t->t.get("namespace").equals(addReq.getProjectCode())).collect(Collectors.toList());
        if(!list.isEmpty()){
            return R.success();
        }

        MultiValueMap<String, Object> formData = new LinkedMultiValueMap<>();

        // 使用add方法添加表单字段（更适合multipart/form-data）
        formData.add("customNamespaceId", addReq.getProjectCode());
        formData.add("namespaceName", addReq.getProjectName());
        if(StrUtil.isNotBlank(addReq.getIntro())){
            formData.add("namespaceDesc", addReq.getIntro());
        }

        return webClient.post()
                .uri(uriBuilder -> uriBuilder
                        .path("/nacos/v1/console/namespaces")
//                        .queryParam("accessToken", addReq.getNacosToken())
                        .build())
                .header("username", userName)
                .header("password", password)
                .contentType(MediaType.MULTIPART_FORM_DATA)
                .body(BodyInserters.fromMultipartData(formData))
                .retrieve()
                .bodyToMono(String.class)
                .map(NacosUtils::handleResponse)
                .block(Duration.ofSeconds(5));


    }

    @ApiOperation(value = "命名空间编辑")
    @PostMapping("/namespace/edit")
    public R editNamespaces(@Valid @RequestBody NamespaceEditReq addReq) {
            MultiValueMap<String, Object> formData = new LinkedMultiValueMap<>();
            // 使用add方法添加表单字段（更适合multipart/form-data）
            formData.add("namespace", addReq.getNamespace());
            formData.add("namespaceShowName", addReq.getNamespaceShowName());
            formData.add("namespaceDesc", addReq.getNamespaceDesc());
            return webClient.put()
                    .uri(uriBuilder -> uriBuilder
                            .path("/nacos/v1/console/namespaces")
                            .queryParam("accessToken", addReq.getNacosToken())
                            .build())
                    .contentType(MediaType.MULTIPART_FORM_DATA)
                    .body(BodyInserters.fromMultipartData(formData))
                    .retrieve()
                    .bodyToMono(String.class)
                    .map(NacosUtils::handleResponse)
                    .block(Duration.ofSeconds(5));

    }

    @ApiOperation(value = "命名空间删除")
    @PostMapping("/namespace/remove")
    public R removeNamespaces(@Valid @RequestBody NamespaceRemoveReq removeReq) {

        String string = webClient.delete()
                .uri(uriBuilder -> uriBuilder
                        .path("/nacos/v1/console/namespaces")
                        .queryParam("namespaceId", removeReq.getProjectCode())
//                        .queryParam("accessToken", removeReq.getNacosToken())
                        .build())
                .header("username", userName)
                .header("password", password)
                .retrieve()
                .bodyToMono(String.class)
                .block(Duration.ofSeconds(5));
        return NacosUtils.handleResponse(string);

    }

    /**
     * 命名空间列表
     *
     * @return
     */
    @ApiOperation(value = "命名空间列表")
    @GetMapping("/namespaces")
    public R listNamespaces(@PathParam("accessToken") String accessToken) {
        Map r = namespace(accessToken);
        return NacosUtils.handleResponse(r);
    }

    private @Nullable Map namespace(String accessToken) {
        Map r = webClient.get()
                .uri(uriBuilder -> uriBuilder
                        .path("/nacos/v1/console/namespaces")
                        .queryParam("accessToken", accessToken)
                        .build())
                .retrieve()
                .bodyToMono(Map.class)
                .block(Duration.ofSeconds(5));
        return r;
    }

}